package com.ruoyi.web.controller.ai_config;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ai_config.domain.AiTaskConfig;
import com.ruoyi.ai_config.domain.AiConfigParams;
import com.ruoyi.ai_config.domain.AiPromptTemplates;
import com.ruoyi.ai_config.service.IAiTaskConfigService;
import com.ruoyi.ai_config.service.IAiConfigParamsService;
import com.ruoyi.ai_config.service.IAiPromptTemplatesService;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * AI配置统一管理Controller
 *
 * @author lzk
 * @date 2025-06-26
 */
@RestController
@RequestMapping("/ai_config/management")
@Tag(name = "【AI配置统一管理】")
public class AiConfigManagementController extends BaseController
{
    @Autowired
    private IAiTaskConfigService aiTaskConfigService;

    @Autowired
    private IAiConfigParamsService aiConfigParamsService;

    @Autowired
    private IAiPromptTemplatesService aiPromptTemplatesService;

    /**
     * 获取AI配置完整信息（包含参数和模板）
     */
    @Operation(summary = "获取AI配置完整信息")
    @PreAuthorize("@ss.hasPermi('ai_config:management:query')")
    @GetMapping(value = "/complete/{configId}")
    public AjaxResult getCompleteConfig(@PathVariable("configId") Long configId)
    {
        // 获取主配置信息
        AiTaskConfig taskConfig = aiTaskConfigService.selectAiTaskConfigById(configId);
        if (taskConfig == null) {
            return error("配置不存在");
        }

        // 获取参数列表
        AiConfigParams paramQuery = new AiConfigParams();
        paramQuery.setConfigId(configId);
        List<AiConfigParams> params = aiConfigParamsService.selectAiConfigParamsList(paramQuery);

        // 获取模板列表
        AiPromptTemplates templateQuery = new AiPromptTemplates();
        templateQuery.setConfigId(configId);
        List<AiPromptTemplates> templates = aiPromptTemplatesService.selectAiPromptTemplatesList(templateQuery);

        // 组装返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("config", taskConfig);
        result.put("params", params);
        result.put("templates", templates);

        return success(result);
    }

    /**
     * 根据配置ID查询参数列表
     */
    @Operation(summary = "根据配置ID查询参数列表")
    @PreAuthorize("@ss.hasPermi('ai_config:params:list')")
    @GetMapping("/params/{configId}")
    public TableDataInfo getParamsByConfigId(@PathVariable("configId") Long configId)
    {
        AiConfigParams aiConfigParams = new AiConfigParams();
        aiConfigParams.setConfigId(configId);
        List<AiConfigParams> list = aiConfigParamsService.selectAiConfigParamsList(aiConfigParams);
        return getDataTable(list);
    }

    /**
     * 根据配置ID查询模板列表
     */
    @Operation(summary = "根据配置ID查询模板列表")
    @PreAuthorize("@ss.hasPermi('ai_config:prompt:list')")
    @GetMapping("/templates/{configId}")
    public TableDataInfo getTemplatesByConfigId(@PathVariable("configId") Long configId)
    {
        AiPromptTemplates aiPromptTemplates = new AiPromptTemplates();
        aiPromptTemplates.setConfigId(configId);
        List<AiPromptTemplates> list = aiPromptTemplatesService.selectAiPromptTemplatesList(aiPromptTemplates);
        return getDataTable(list);
    }

    /**
     * 批量保存AI配置（包含参数和模板）
     */
    @Operation(summary = "批量保存AI配置")
    @PreAuthorize("@ss.hasPermi('ai_config:management:save')")
    @Log(title = "AI配置统一管理", businessType = BusinessType.UPDATE)
    @PostMapping("/batch-save")
    public AjaxResult batchSave(@RequestBody Map<String, Object> data)
    {
        try {
            // 获取配置ID
            Long configId = Long.valueOf(data.get("configId").toString());

            // 保存参数
            if (data.containsKey("params")) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> paramsList = (List<Map<String, Object>>) data.get("params");
                for (Map<String, Object> paramMap : paramsList) {
                    AiConfigParams param = new AiConfigParams();
                    param.setConfigId(configId);
                    param.setParamKey(paramMap.get("paramKey").toString());
                    param.setParamValue(paramMap.get("paramValue") != null ? paramMap.get("paramValue").toString() : null);
                    param.setParamType(paramMap.get("paramType") != null ? paramMap.get("paramType").toString() : "string");
                    param.setParamDescription(paramMap.get("paramDescription") != null ? paramMap.get("paramDescription").toString() : null);
                    param.setIsRequired((long) (paramMap.get("isRequired") != null ? Integer.valueOf(paramMap.get("isRequired").toString()) : 0));
                    param.setSortOrder((long) (paramMap.get("sortOrder") != null ? Integer.valueOf(paramMap.get("sortOrder").toString()) : 0));

                    if (paramMap.get("id") != null) {
                        param.setId(Long.valueOf(paramMap.get("id").toString()));
                        aiConfigParamsService.updateAiConfigParams(param);
                    } else {
                        aiConfigParamsService.insertAiConfigParams(param);
                    }
                }
            }

            // 保存模板
            if (data.containsKey("templates")) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> templatesList = (List<Map<String, Object>>) data.get("templates");
                for (Map<String, Object> templateMap : templatesList) {
                    AiPromptTemplates template = new AiPromptTemplates();
                    template.setConfigId(configId);
                    template.setTemplateName(templateMap.get("templateName").toString());
                    template.setPromptContent(templateMap.get("promptContent").toString());
                    template.setTemplateType(templateMap.get("templateType") != null ? templateMap.get("templateType").toString() : "system");
                    template.setVariables(templateMap.get("variables") != null ? templateMap.get("variables").toString() : null);

                    if (templateMap.get("id") != null) {
                        template.setId(Long.valueOf(templateMap.get("id").toString()));
                        aiPromptTemplatesService.updateAiPromptTemplates(template);
                    } else {
                        aiPromptTemplatesService.insertAiPromptTemplates(template);
                    }
                }
            }

            return success("保存成功");
        } catch (Exception e) {
            return error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 复制配置（包含参数和模板）
     */
    @Operation(summary = "复制配置")
    @PreAuthorize("@ss.hasPermi('ai_config:management:copy')")
    @Log(title = "AI配置复制", businessType = BusinessType.INSERT)
    @PostMapping("/copy/{configId}")
    public AjaxResult copyConfig(@PathVariable("configId") Long configId, @RequestBody Map<String, String> data)
    {
        try {
            // 获取原配置
            AiTaskConfig originalConfig = aiTaskConfigService.selectAiTaskConfigById(configId);
            if (originalConfig == null) {
                return error("原配置不存在");
            }

            // 创建新配置
            AiTaskConfig newConfig = new AiTaskConfig();
            newConfig.setConfigName(data.get("configName"));
            newConfig.setTaskType(originalConfig.getTaskType());
            newConfig.setDescription(originalConfig.getDescription());
            newConfig.setIsActive(0L); // 默认禁用

            aiTaskConfigService.insertAiTaskConfig(newConfig);
            Long newConfigId = newConfig.getId();

            // 复制参数
            AiConfigParams paramQuery = new AiConfigParams();
            paramQuery.setConfigId(configId);
            List<AiConfigParams> originalParams = aiConfigParamsService.selectAiConfigParamsList(paramQuery);
            for (AiConfigParams originalParam : originalParams) {
                AiConfigParams newParam = new AiConfigParams();
                newParam.setConfigId(newConfigId);
                newParam.setParamKey(originalParam.getParamKey());
                newParam.setParamValue(originalParam.getParamValue());
                newParam.setParamType(originalParam.getParamType());
                newParam.setParamDescription(originalParam.getParamDescription());
                newParam.setIsRequired(originalParam.getIsRequired());
                newParam.setSortOrder(originalParam.getSortOrder());
                aiConfigParamsService.insertAiConfigParams(newParam);
            }

            // 复制模板
            AiPromptTemplates templateQuery = new AiPromptTemplates();
            templateQuery.setConfigId(configId);
            List<AiPromptTemplates> originalTemplates = aiPromptTemplatesService.selectAiPromptTemplatesList(templateQuery);
            for (AiPromptTemplates originalTemplate : originalTemplates) {
                AiPromptTemplates newTemplate = new AiPromptTemplates();
                newTemplate.setConfigId(newConfigId);
                newTemplate.setTemplateName(originalTemplate.getTemplateName());
                newTemplate.setPromptContent(originalTemplate.getPromptContent());
                newTemplate.setTemplateType(originalTemplate.getTemplateType());
                newTemplate.setVariables(originalTemplate.getVariables());
                aiPromptTemplatesService.insertAiPromptTemplates(newTemplate);
            }

            // 修复：使用Map包装返回数据，而不是直接传递两个参数
            Map<String, Object> result = new HashMap<>();
            result.put("message", "复制成功");
            result.put("newConfigId", newConfigId);
            return success(result);
        } catch (Exception e) {
            return error("复制失败：" + e.getMessage());
        }
    }

    /**
     * 删除参数
     */
    @Operation(summary = "删除参数")
    @PreAuthorize("@ss.hasPermi('ai_config:params:remove')")
    @Log(title = "AI配置参数", businessType = BusinessType.DELETE)
    @DeleteMapping("/params/{ids}")
    public AjaxResult removeParams(@PathVariable Long[] ids)
    {
        return toAjax(aiConfigParamsService.deleteAiConfigParamsByIds(ids));
    }

    /**
     * 删除模板
     */
    @Operation(summary = "删除模板")
    @PreAuthorize("@ss.hasPermi('ai_config:prompt:remove')")
    @Log(title = "AI提示词模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/templates/{ids}")
    public AjaxResult removeTemplates(@PathVariable Long[] ids)
    {
        return toAjax(aiPromptTemplatesService.deleteAiPromptTemplatesByIds(ids));
    }

    /**
     * 预览生成的提示词
     */
    @Operation(summary = "预览生成的提示词")
    @PreAuthorize("@ss.hasPermi('ai_config:management:preview')")
    @PostMapping("/preview/{configId}")
    public AjaxResult previewPrompt(@PathVariable("configId") Long configId, @RequestBody Map<String, Object> variables)
    {
        try {
            // 获取模板
            AiPromptTemplates templateQuery = new AiPromptTemplates();
            templateQuery.setConfigId(configId);
            List<AiPromptTemplates> templates = aiPromptTemplatesService.selectAiPromptTemplatesList(templateQuery);

            Map<String, String> result = new HashMap<>();
            for (AiPromptTemplates template : templates) {
                String content = template.getPromptContent();

                // 简单的变量替换（可以根据需要使用更复杂的模板引擎）
                if (variables != null) {
                    for (Map.Entry<String, Object> entry : variables.entrySet()) {
                        String placeholder = "{{" + entry.getKey() + "}}";
                        content = content.replace(placeholder, entry.getValue() != null ? entry.getValue().toString() : "");
                    }
                }

                result.put(template.getTemplateType() + "_" + template.getId(), content);
            }

            return success(result);
        } catch (Exception e) {
            return error("预览失败：" + e.getMessage());
        }
    }
}